package com.cet.algorithm.动态规划.背包问题;

/**
 * @program: cet-practice
 * @description: 背包问题01
 * @author: 陈恩涛
 * @create: 2023-10-17 10:06
 **/
public class BagProblem01 {

    public static void main(String[] args) {
        int[] weight = {1,3,4};
        int[] value = {15,20,30};
        int bagSize = 4;
        testWeightBagProblem(weight,value,bagSize);
    }

    /**
     * 动态规划获得结果
     * @param weight  物品的重量
     * @param value   物品的价值
     * @param bagSize 背包的容量
     */
    public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){

        //1.dp[i][j] i件物品放到容量为j的背包，最大价值为多少
        //2.dp[i][j] = max{dp[i-1][j], d[i - 1][j - weight[i]] + value[i]}
        //3.dp[i][0] = 0; j >= weight[0] dp[0][j] = weight[0];

        //初始化
        // 0-bagSize，所以初始化时dp的列数为bagSize + 1
        int[][] dp = new int[weight.length][bagSize + 1];

        for (int i = 1; i < dp[0].length; i++) {
            if (i >= weight[0]) {
                dp[0][i] = value[0];
            } else {
                dp[0][i] = 0;
            }
        }

        // 从左上往右下进行遍历
        // 先物品后背包大小

        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                // 当心放不进去的场景
                if (j >= weight[i]) {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }

        // 打印01背包dp数组
        for (int i = 0; i < weight.length; i++) {
            for (int j = 0; j <= bagSize; j++) {
                System.out.print(dp[i][j] + "\t");
            }
            System.out.println("\n");
        }
    }
}
